package com.situ.web.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/deleteStudent")
public class DeleteStudentServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("DeleteStudentServlet.service()");
		// http://localhost:8080/Java1912Web/deleteStudent?id=12
		// ?后面的id是传递的参数
		String id = req.getParameter("id");
		System.out.println("id:" + id);
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "delete from student where id=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1, Integer.parseInt(id));
			int count = preparedStatement.executeUpdate();
			if (count == 1) {
				System.out.println("删除成功");
			} else {
				System.out.println("删除失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
		
		// 删除完成之后，应该查询所有学生展示，就是请求 /Java1912Web/findAllStudent
		// resp.sendRedirect("/Java1912Web/findAllStudent");
		// req.getContextPath() 返回当前项目名字
		resp.sendRedirect(req.getContextPath() + "/findAllStudent");
	}
}
